<template>
  <div>
    <form action="">
      姓名：<input type="text" v-model="stu.uname" /><br />
      年龄：<input type="text" v-model.number="stu.age" /><br />
      性别：<input type="radio" name="sex" value="男" v-model="stu.sex" />男
      <input type="radio" name="sex" value="女" v-model="stu.sex" />女
      <br />
      <button @click.prevent="add">添加/修改</button>
    </form>
    <br />
    <table border="1" rules="all" cellpadding="3" width="500">
      <thead>
        <tr>
          <th>ID</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="item in list" :key="item.id">
          <td>{{ item.id }}</td>
          <td>{{ item.uname }}</td>
          <td>{{ item.age }}</td>
          <td>{{ item.sex }}</td>
          <td>
            <button @click="del(item.id)">删除</button>&nbsp;
            <button @click="edit(item.id)">编辑</button>
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script>
export default {
  data() {
    return {
      list: [
        { id: 2, uname: "张三", age: 20, sex: "男" },
        { id: 3, uname: "李四", age: 21, sex: "女" },
      ],
      // 用于存储表单中的数据
      stu: {
        uname: "",
        age: "",
        sex: "男",
      },
      id: null, // id 是null就是添加操作；   id如果是真实的id值，则表示修改
    };
  },
  methods: {
    del(id) {
      this.list = this.list.filter((item) => item.id !== id);
    },
    // 下面的方法，既可以做添加、也可以做修改
    add() {
      if (this.id === null) {
       
        // 做添加操作
        this.stu.id = +new Date();
        this.list.push({ ...this.stu });
      } else {
        // 做修改操作
        // console.log(this.id);
        // console.log(this.stu);
        let index = this.list.findIndex((item) => item.id === this.id);
        this.list.splice(index, 1, { ...this.stu });
        this.id = null;
      }
      this.stu = {
        uname: "",
        age: "",
        sex: "男",
      };
    },
    edit(id) {
      let row = this.list.find((item) => item.id === id);
      // console.log(row);
      this.stu = { ...row };
      this.id = row.id;
    },
  },
};
</script>

<style>
</style>